import { useMemo, useRef, useState } from 'react';
import { ConfigStyle, MainComStyle, CodeColorStyle } from './style';
import { Button, Form, Switch, message } from 'antd';
import { createTypeNode } from './utils';

const str = `
{
	"name": "小小怪下士",
	"age": 13,
	"info": {
		"height": 1.5,
		"vue": {
			"name": "react"
		}
	},
	"bar": [123, { "aaa": 100 }],
	"arr": ["a"],
	"text": [{ "bar": 18 }, { "color": "red" }]
}
`;

const JsonToType = () => {
	const [textValue, setTextValue] = useState(str);
	const [optional, setOptional] = useState(false);
	const [origin, setOrigin] = useState<string>('');
	const textRef = useRef<HTMLTextAreaElement>();

	const originJson = useMemo(() => {
		if (origin) {
			try {
				const jsonObject = JSON.parse(origin);
				// return createTypeDom(jsonObject, { optional });
				return createTypeNode(jsonObject, { optional });
			} catch (error) {
				message.warning('格式不正确');
				console.log(error);
			}
		}
	}, [origin, optional]);

	const transition = () => {
		const value = textRef.current.value;
		if (value) {
			setOrigin(value);
		} else {
			message.warning('json为空');
		}
	};

	const handleKeyDown = (e: any) => {
		if (e.key === 'Tab') {
			e.preventDefault(); // 阻止默认行为，即不让焦点离开textarea
			const start = e.target.selectionStart;
			const end = e.target.selectionEnd;
			// 更新文本：文本起始部分 + 制表符 + 文本结束部分
			const newText = textValue.substring(0, start) + '\t' + textValue.substring(end);
			setTextValue(newText);

			// 异步设置光标位置，因为直接设置可能不生效
			setTimeout(() => {
				e.target.selectionStart = e.target.selectionEnd = start + 1;
			}, 0);
		}
	};

	return (
		<>
			<ConfigStyle>
				<Form layout="inline">
					<Form.Item label="是否可选">
						<Switch value={optional} onChange={(checked) => setOptional(checked)} />
					</Form.Item>
				</Form>
			</ConfigStyle>

			<MainComStyle>
				<div className="origin-json">
					<textarea
						className="json-text"
						ref={textRef}
						value={textValue}
						onChange={(event) => {
							const value = event.target.value;
							setTextValue(value);
						}}
						onKeyDown={handleKeyDown}
					/>
				</div>
				<Button type="primary" onClick={transition}>
					转换
				</Button>
				<div className="type-code">
					<CodeColorStyle>{originJson}</CodeColorStyle>
				</div>
			</MainComStyle>
		</>
	);
};

export default JsonToType;
